package com.s.core.root;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.Data;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Data
public class As {
    private static volatile As me;
    private List<S> sList;

    private As() {
        sList = com.s.S.persistService.loadS().getSList();
    }

    public static As me() {
        if (me == null) {
            synchronized (As.class) {
                if (me == null) {
                    me = new As();
                }
            }
        }
        return me;
    }

    public List<String> list() {
        return sList.stream().map(S::getCode).collect(Collectors.toList());
    }

    public S get(String code) {
        List<S> sListCode = sList.stream().filter(s -> s.getCode().equals(code)).
                collect(Collectors.toList());
        if (CollectionUtils.isEmpty(sListCode)) {
            return null;
        }
        return sListCode.get(0);
    }

    public void update(String code, int p) {
        Map<Integer, List<S>> map = Maps.newHashMap();
        map.put(1, sList.stream().filter(s -> s.getP() == 1).collect(Collectors.toList()));
        map.put(2, sList.stream().filter(s -> s.getP() == 2).collect(Collectors.toList()));
        map.put(3, sList.stream().filter(s -> s.getP() == 3).collect(Collectors.toList()));
        S s = get(code);
        if (s == null) {
            map.get(p).add(new S(code, p));
        } else if (s.getP() == p) {
            map.get(p).removeIf(t -> t.getCode().equals(code));
        } else {
            map.get(s.getP()).removeIf(t -> t.getCode().equals(code));
            map.get(p).add(new S(code, p));
        }
        sList = Lists.newArrayList();
        sList.addAll(map.get(1));
        sList.addAll(map.get(2));
        sList.addAll(map.get(3));
        com.s.S.persistService.saveS();
    }
}
